﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KWIC;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace Hestia_Cyberminer
{
    /// <summary>
    /// This is the class for the Dashboard.aspx Page(Code Behind)
    /// </summary>
    /// The following was created by mgsurya developed on the machineMGSURYA-PC on 12/4/2012, 8:21 AM
    public partial class Dashboard : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        /// <summary>
        /// Handles the Click event of the onaddURLbtn control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        /// The following was created by mgsurya developed on the machineMGSURYA-PC on 12/4/2012, 8:23 AM
        protected void onaddURLbtn_Click(object sender, EventArgs e)
        {   
            /* Will store the Alhabetized Noise Eliminated Cicular Shifts. 
             */
            List<string> ANECS = new List<string>();
            /* hyperlink string to store the hyperlink. Set to and empty string intially.
             */
            string hyperlink = "";

            /* If all the text box are filled the execute the if condition.
             */
            if (txtBoxIdentifier1.Text.Trim().Count() > 0
                && txtBoxIdentifier2.Text.Trim().Count() > 0
                && txtBoxIdentifier3.Text.Trim().Count() > 0)
            {
                /* Create the hyperlink
                 */
                hyperlink = "http://" + txtBoxIdentifier1.Text + '.' + txtBoxIdentifier2.Text + '.' + txtBoxIdentifier3.Text + DomainDropDownList.SelectedValue;
                /* Reset the labels 
                 */
                resetLabelsAndLists();
                /* Make the lable lblBadUrlOrder invisible
                 */
                lblBadUrlOrder.Visible = false;
                /* Make the lable lblNoIdentifierError invisible
                 */
                lblNoIdentifierError.Visible = false;
                /* get the Alphabetized Nosie Eliminated Circular Shifts by invoking the getANECS method 
                 */
                ANECS = getANECS(txtBoxIdentifier1.Text, txtBoxIdentifier2.Text, txtBoxIdentifier3.Text);
                /* Add the ANCES list and the hyperlink to the database. For example,
                 * "www hcyber codeplex", http://www.hcyber.codeplex.com
                 * "hcyber codeplex www ", http://www.hcyber.codeplex.com
                 * "codeplex www hcyber", http://www.hcyber.codeplex.com
                 */
                addToDB(ANECS, hyperlink);
            }
            /* If only the first two textboxes were filled then execute this if statement.
             */
            else if (txtBoxIdentifier1.Text.Trim().Count() > 0
                    && txtBoxIdentifier2.Text.Trim().Count() > 0
                    && txtBoxIdentifier3.Text.Trim().Count() == 0)
            {
                /* Create the hyperlink
                 */
                hyperlink = "http://" + txtBoxIdentifier1.Text + '.' + txtBoxIdentifier2.Text + DomainDropDownList.SelectedValue;
                /* Reset the labels 
                 */
                resetLabelsAndLists();
                /* Make the lable lblBadUrlOrder invisible
                 */
                lblBadUrlOrder.Visible = false;
                /* Make the lable lblNoIdentifierError invisible
                 */
                lblNoIdentifierError.Visible = false;
                /* get the Alphabetized Nosie Eliminated Circular Shifts by invoking the getANECS method 
                 */
                ANECS = getANECS(txtBoxIdentifier1.Text, txtBoxIdentifier2.Text, txtBoxIdentifier3.Text);
                 /* Add the ANCES list and the hyperlink to the database. For example,
                  * "www amazon", http://www.amazon.com
                  * "amazon www", http://www.amazon.com
                  */
                addToDB(ANECS, hyperlink);
            }
            /* If only the first textbox is filled then execute this if statement.
             */
            else if (txtBoxIdentifier1.Text.Trim().Count() > 0
                    && txtBoxIdentifier2.Text.Trim().Count() == 0
                    && txtBoxIdentifier3.Text.Trim().Count() == 0)
            {
                /* Create the hyperlink
                 */
                hyperlink = "http://" + txtBoxIdentifier1.Text + DomainDropDownList.SelectedValue;
                /* Reset the labels 
                 */
                resetLabelsAndLists();
                /* Make the lable lblNoIdentifierError invisible
                 */
                lblBadUrlOrder.Visible = false;
                /* Make the lable lblNoIdentifierError invisible
                 */
                lblNoIdentifierError.Visible = false;
                /* get the Alphabetized Nosie Eliminated Circular Shifts by invoking the getANECS method 
                 */
                ANECS = getANECS(txtBoxIdentifier1.Text, txtBoxIdentifier2.Text, txtBoxIdentifier3.Text);
                /* Add the ANCES list and the hyperlink to the database. For example,
                  * "amazon", http://amazon.com
                  */
                addToDB(ANECS, hyperlink);
            }
            /* If the textboxes were not filled in order, Warning scenario 1: only the textbox 2 is filled
             */
            else if (txtBoxIdentifier1.Text.Trim().Count() == 0
                    && txtBoxIdentifier2.Text.Trim().Count() > 0
                    && txtBoxIdentifier3.Text.Trim().Count() == 0)
            {
                /* Reset the labels 
                 */
                resetLabelsAndLists();
                /* Make the lable lblNoIdentifierError visible
                 */
                lblBadUrlOrder.Visible = true;
                /* get the Alphabetized Nosie Eliminated Circular Shifts by invoking the getANECS method 
                 */
                lblNoIdentifierError.Visible = false;
            }
            /* If only the texboxes 1 and 3 were filled (warning scenario 2)  
             */
            else if (txtBoxIdentifier1.Text.Trim().Count() > 0
                && txtBoxIdentifier2.Text.Trim().Count() == 0
                && txtBoxIdentifier3.Text.Trim().Count() > 0)
            {
                /* Reset the labels 
                 */
                resetLabelsAndLists();
                /* Make the lable lblBadUrlOrder visible
                 */
                lblBadUrlOrder.Visible = true;
                /* Make the lable lblNoIdentifierError invisible
                 */
                lblNoIdentifierError.Visible = false;
            }
            /* If the texboxes are empty
             */
            else if (txtBoxIdentifier1.Text.Trim().Count() == 0
                    && txtBoxIdentifier2.Text.Trim().Count() == 0
                    && txtBoxIdentifier3.Text.Trim().Count() == 0)
            {
                /* Reset the labels 
                 */
                resetLabelsAndLists();
                /* Make the lable lblNoIdentifierError visible
                 */
                lblNoIdentifierError.Visible = true;
            }
        }

        /// <summary>
        /// Adds to DB.
        /// </summary>
        /// <param name="ANECS">The ANECS.</param>
        /// <param name="hyperLink">The hyper link.</param>
        /// The following was created by mgsurya developed on the machineMGSURYA-PC on 12/4/2012, 8:27 AM
        private void addToDB(List<string> ANECS, string hyperLink)
        {
            bool success = true;
            bool notExists = false;
            /* Gets the Sql Connection String stord in the web.config file under the appSettings Tab.
             * Gives us the ability keep the database configurations outside the Web Application. Helpful when 
             * migrating a database.
             */
            string connectionString = ConfigurationManager.AppSettings["SQLSERVER_CONNECTION_STRING"];
            /* Create a myCommand Object of type SqlCommand.
             */
            SqlCommand myCommand = new SqlCommand();
            /* Reset the labels 
                 */
            resetLabelsAndLists();

            try
            {
                /* Create a dataTable Object of type DataTable.
                 */
                DataTable dataTable = new DataTable();
                /* Create a myConnection Object of type SqlConnection.
                 */
                SqlConnection myConnection = new SqlConnection(connectionString);
                /*
                 */
                string mySelectQuery = "SELECT url_hyplerlink FROM url_info WHERE url_hyplerlink='"
                                            + hyperLink + "'";
                /* Set myCommand's CommandText Property to mySelectQuery string.
                 */
                myCommand.CommandText = mySelectQuery;
                /* Save the Sql Connection String into myCommand Object's Connection Property 
                 */
                myCommand.Connection = myConnection;
                /* Open the database connection
                 */
                myConnection.Open();
                /* Fill the datatable upon query execution.
                 */
                SqlDataAdapter ad = new SqlDataAdapter(myCommand);
                /* Fill the datatable upon query execution.
                 */
                ad.Fill(dataTable);
                /* if the row count is greater than zero the entry does not exist.
                 */
                if (dataTable.Rows.Count > 0)
                    notExists = true;
                /* Execute the Sql query.
                 */
                myCommand.ExecuteNonQuery();
                /* Close the Database connection.
                 */
                myCommand.Connection.Close();
                /* if the entry does not exist execute the if condition 
                 */
                if (!notExists)
                {
                    /* Make lablel lblInsertExists invisible
                     */
                    lblInsertExists.Visible = false;
                    /* Make lablel lblDBTranscationStatus visible
                     */
                    lblDBTranscationStatus.Visible = true;
                    
                    foreach (string sentence in ANECS)
                    {
                        
                        string myInsertQuery = "INSERT INTO url_info (url_descriptor,url_hyplerlink,date_modified)"
                                               + "Values('" + sentence + "','" + hyperLink + "','"
                                               + DateTime.Now.ToShortDateString() + "')";
                        
                        myCommand.CommandText = myInsertQuery;
                        
                        myCommand.Connection = myConnection;
                        
                        myConnection.Open();
                        
                        myCommand.ExecuteNonQuery();
                        
                        myCommand.Connection.Close();

                    }
                }
                /* if entry exists
                 */
                else if (notExists)
                {
                    /* Make label lblDBTranscationStatus invisible
                     */
                    lblDBTranscationStatus.Visible = false;
                    /* Make label lblInsertExists visible
                     */
                    lblInsertExists.Visible = true;
                    /* Set lblInsertExists label's text property 
                     */
                    lblInsertExists.Text = "Hyperlink enter already exists in the Database!";

                }

            }
            /* Catch Exceptions.
             */
            catch (Exception e)
            {
                
                success = false;
                
                lblDBTranscationStatus.Visible = true;
                
                lblDBTranscationStatus.Text = "Database update failed! Error Message: " + e.Message;
            }
            
            finally
            {
                if (success == true) { lblDBTranscationStatus.Text = "Database was successfully updated!"; }
                
                // May choose to close the sql connection here but chose not to handle it. As am gaunranteed 
                // of no such errors.
            }
        }

        /// <summary>
        /// Resets the labels and lists.
        /// </summary>
        /// The following was created by mgsurya developed on the machineMGSURYA-PC on 12/4/2012, 8:32 AM
        private void resetLabelsAndLists()
        {
            lblDBTranscationStatus.Visible = false;
        }

        /// <summary>
        /// Gets the ANECS.
        /// </summary>
        /// <param name="id1">The id1.</param>
        /// <param name="id2">The id2.</param>
        /// <param name="id3">The id3.</param>
        /// <returns></returns>
        /// The following was created by mgsurya developed on the machineMGSURYA-PC on 12/4/2012, 8:32 AM
        private List<string> getANECS(string id1, string id2, string id3)
        {
            
            string s = "";

            /* Generate the Descriptors
             */
            if (id1.Count() > 0 && id2.Count() > 0 && id3.Count() > 0)
            {
                
                s = id1.TrimStart().TrimEnd() + " " + id2.TrimStart().TrimEnd() + " " + id3.TrimStart().TrimEnd();
            }
            
            if (id1.Count() > 0 && id2.Count() > 0 && id3.Count() == 0)
            {
                
                s = id1.TrimStart().TrimEnd() + " " + id2.TrimStart().TrimEnd();
            }
            
            if (id1.Count() > 0 && id2.Count() == 0 && id3.Count() == 0)
            {
               
                s = id1.TrimStart().TrimEnd();
            }
            
            List<string> Sentence = new List<string>();
            
            List<string> TCSS = new List<string>();
            
            List<List<string>> NETCSSRS = new List<List<string>>();
            
            List<string> TCSSOS = new List<string>();
            
            List<string> ANETCSSRS = new List<string>();

            CircularShift CShift = new CircularShift();
            
            NoiseElimator NE = new NoiseElimator();
           
            Alphabetizer Alpha = new Alphabetizer();

            Sentence.Add(s);
            
            displaySentence(s);

            TCSS = CShift.getCS(Sentence);

            TCSSOS.AddRange(TCSS);
            
            TCSSOS.AddRange(Sentence);

            NETCSSRS = NE.getNECS(TCSSOS);

            ANETCSSRS = Alpha.alphabetize(NETCSSRS[0]);
            
            return ANETCSSRS;
        }

        /// <summary>
        /// Displays the sentence.
        /// </summary>
        /// <param name="s">The s.</param>
        /// The following was created by mgsurya developed on the machineMGSURYA-PC on 12/4/2012, 8:35 AM
        private void displaySentence(string s)
        {
            lblSentence.Text = "Generated descriptor: " + s;
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            /* Gets the Sql Connection String stord in the web.config file under the appSettings Tab.
             * Gives us the ability keep the database configurations outside the Web Application. Helpful when 
             * migrating a database.
             */
            lblUserNotExistsError.Visible = false;
            DataEntryPanel.Visible = false;

            string connectionString = ConfigurationManager.AppSettings["SQLSERVER_CONNECTION_STRING"];
            /* Create a myCommand Object of type SqlCommand.
             */
            SqlCommand myCommand = new SqlCommand();

            try { 

                /* Create a dataTable Object of type DataTable.
                 */
                DataTable dataTable = new DataTable();
                /* Create a myConnection Object of type SqlConnection.
                 */
                SqlConnection myConnection = new SqlConnection(connectionString);
                /*
                 */
                string mySelectQuery = "SELECT admin_name, admin_password FROM admin WHERE (admin_name = '" 
                                        + txtBoxAdminName.Text  + "' AND admin_password = '" + txtBoxAdminPass.Text + "')";
                /* Set myCommand's CommandText Property to mySelectQuery string.
                 */
                myCommand.CommandText = mySelectQuery;
                /* Save the Sql Connection String into myCommand Object's Connection Property 
                 */
                myCommand.Connection = myConnection;
                /* Open the database connection
                 */
                myConnection.Open();
                /* Fill the datatable upon query execution.
                 */
                SqlDataAdapter ad = new SqlDataAdapter(myCommand);
                /* Fill the datatable upon query execution.
                 */
                ad.Fill(dataTable);
                /* Execute the Sql query.*/

                if (dataTable.Rows.Count == 1)
                {
                    DataEntryPanel.Visible = true;
                }
                else {
                    lblUserNotExistsError.Visible = true;
                }

                myCommand.ExecuteNonQuery();
                /* Close the Database connection.
                 */
                myCommand.Connection.Close();
            }
            catch (Exception e2) { }
            finally { }
            
        }

       

        
    }
}